
import re
import json
from django.contrib.auth import login, logout, authenticate
from django.http import JsonResponse
from django.views import View
from django_redis import get_redis_connection

from apps.users.models import User, Address
from meiduo_test.utils.secret import SecretOauth
from meiduo_test.utils.views import LoginRequiredJSONMixin
from apps.users.utils import generate_verify_email_url
from celery_tasks.email.tasks import send_verify_email


class UsernameCountView(View):
    """　
    判断用户名是否重复接口文档：
        路由：　　　/usernames/<username:username>/count/
        请求方式：  GET
        参数：路径参数　　　username
        响应结果：  code errmsg  count
    """
    def get(self, request,username):
        # 查询username在数据库中的个数
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            return JsonResponse({'code':400, 'errmsg':'访问数据库失败'})

        # 返回响应数据
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'count':count})


class MobileCountView(View):
    """
    手机号重复注册接口文档：
        路由：    /mobiles/<mobile:mobile>/count
        请求方式：GET
        参数：路径参数　　　mobile
        响应结果:  code errmsg count
    """
    def get(self, request, mobile):
        try:
            count = User.objects.filter(mobile=mobile).count()
        except Exception as e:
            print(e)
            return JsonResponse({'code':400, 'errmsg':'访问数据库失败'})
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'count':count})


class RegisterView(View):
    """
    用户注册接口文档：
        路由：　　　　/register
        请求方式：   POST
        参数：json  　username  password   password2  mobile  sms_code  allow
        响应结果：html   code  errmsg
    """
    def post(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        # 提取参数
        username = json_dict.get('username')
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        mobile = json_dict.get('mobile')
        allow = json_dict.get('allow')
        sms_code = json_dict.get('sms_code')

        # 校验参数
        if not all([username, password, password2, mobile, sms_code]):
            return JsonResponse({'code':400, 'errmsg':'缺少必传参数'})
        # username检验
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return JsonResponse({'code': 400, 'errmsg': 'username格式有误!'})

        # password检验
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return JsonResponse({'code': 400, 'errmsg': 'password格式有误!'})

        # password2 和 password
        if password != password2:
            return JsonResponse({'code': 400, 'errmsg': '两次输入不对!'})
        # mobile检验
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': 'mobile格式有误!'})
        # allow检验
        if allow != True:
            return JsonResponse({'code': 400, 'errmsg': 'allow格式有误!'})

        # 判断短信验证码是否正确：跟图形验证码的验证一样的逻辑
        # 提取服务端存储的短信验证码：以前怎么存储，现在就怎么提取
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)  # sms_code_server是bytes
        # 判断短信验证码是否过期
        if not sms_code_server:
            return JsonResponse({'code': 400, 'errmsg': '短信验证码失效'})
        # 对比用户输入的和服务端存储的短信验证码是否一致
        if sms_code != sms_code_server.decode():
            return JsonResponse({'code': 400, 'errmsg': '短信验证码有误'})

        # 注册核心逻辑
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '注册失败!'})

        # 实现状态保持
        login(request, user)

        # 返回响应结果
        # 生成响应对象
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})

        # 在响应对象中设置用户名信息.
        # 将用户名写入到 cookie，有效期 14 天
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)

        # 返回响应结果
        return response


class LoginView(View):

    def post(self, request):
        # 1, 接收参数, 提取参数
        json_dict = json.loads(request.body.decode())
        username = json_dict.get('username')
        password = json_dict.get('password')
        remembered = json_dict.get('remembered')

        # 2，校验参数(判空)
        if not all([username, password]):
            return JsonResponse({'code':400, 'errmsg':'参数不齐'})

        # 多账号登录
        if re.match(r'^1[3-9]\d{9}$', username):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'


        # 3， 与数据库进行判断，看用户名和密码是否一致，认证是否能够登录－－authenticate(密码会加密)
        user = authenticate(request, username=username, password=password)
        if user is None:
            return JsonResponse({'code': 400, 'errmsg': '用户名或密码错误'})

        # 4，保持回话状态
        login(request, user)

        # 5,是否记住登录
        if remembered != True:
            request.session.set_expiry(0)
        else:
            request.session.set_expiry(None)

        # 6,返回响应结果
        response = JsonResponse({'code': 0, 'errmsg': '登录成功'})
        response.set_cookie('username', user.username, max_age=24 * 14 * 3600)
        return response

class LogoutView(View):
    """定义退出登录的接口"""

    def delete(self, request):
        """实现退出登录逻辑"""

        # 清理 session
        logout(request)

        # 创建 response 对象.
        response = JsonResponse({'code':0, 'errmsg':'ok'})

        # 调用对象的 delete_cookie 方法, 清除cookie
        response.delete_cookie('username')

        # 返回响应
        return response


class UserInfoView(LoginRequiredJSONMixin, View):
    # 用户中心
    def get(self, request):

        info_data =  {
                "username": request.user.username,
                "mobile": request.user.mobile,
                "email": request.user.email,
                "email_active": request.user.email_active
            }
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            "info_data":info_data
        })


class EmailView(View):
    """添加邮箱"""

    def put(self, request):
        """实现添加邮箱逻辑"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        email = json_dict.get('email')

        # 校验参数
        if not email:
            return JsonResponse({'code': 400,
                                      'errmsg': '缺少email参数'})
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({'code': 400,
                                      'errmsg': '参数email有误'})
        # 赋值 email 字段
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400,
                                      'errmsg': '添加邮箱失败'})
        # 从 celery_tasks 中导入:
        # 调用发送的函数:
        verify_url = generate_verify_email_url(request)
        send_verify_email.delay(email, verify_url)

        # 响应添加邮箱结果
        return JsonResponse({'code': 0,
                                  'errmsg': 'ok'})


class VerifyEmailView(View):
    def put(self, request):
        # - 1.接收 token
        token = request.GET.get('token')

        if not token:
            return JsonResponse({'code': 400, 'errmsg': 'token缺少'})

        # - 2.解密
        data_dict = SecretOauth().loads(token)

        # - 4.去数据库对比 user_id,email
        try:
            user = User.objects.get(pk=data_dict.get('user_id'), email=data_dict.get('email'))
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '参数有误!'})

        # - 5.修改激活状态
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            return JsonResponse({'code': 0, 'errmsg': '激活失败!'})


        return JsonResponse({'code': 0, 'errmsg': '激活成功!'})


class CreateAddressView(View):
    """新增地址"""

    def post(self, request):

        # 获取地址个数:
        count = Address.objects.filter(user=request.user,is_deleted=False).count()

        # 判断是否超过地址上限：最多20个
        if count >= 20:
            return JsonResponse({'code': 400, 'errmsg': '超过地址数量上限'})

        # 1. 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 2,校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '参数mobile有误'})

        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400, 'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400, 'errmsg': '参数email有误'})

        # 保存地址信息
        try:
            address = Address.objects.create(
            user=request.user,
            title=receiver,
            receiver=receiver,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            place=place,
            mobile=mobile,
            tel=tel,
            email=email
            )

            # 设置默认地址
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()

        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '新增地址失败'})

        # 新增地址成功，将新增的地址响应给前端实现局部刷新
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应保存结果
        return JsonResponse({'code': 0, 'errmsg': '新增地址成功', 'address':address_dict})


class AddressView(View):
    def get(self, request):
        # 获取所有地址
        addresses = Address.objects.filter(user=request.user, is_deleted=False)

        # 创建空列表
        addresses_dict_list = []

        # 遍历
        for address in addresses:
            addresses_dict_list.append({
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            })

        return JsonResponse({'code': 0, 'errmsg': 'ok', 'addresses': addresses_dict_list,
                             'default_address_id': request.user.default_address_id})







